from django.views import View
from django.http.response import JsonResponse
from . import models
import json
from django.db.models import F,Q
from django.db.models import Max,Min,Avg,Count,Sum

class Author(View):
    ###查询数据
    def get(self,request):
        #根据作者姓名查询所写的文章的标题和文章数量
        author_name = json.loads(request.body).get('name')

        info = models.Article.objects.filter(author__name=author_name)

        #返回作者所写的文章标题和文章数量
        response = {
            'title_list':[],
            'count':0
        }

        for article in info.all():
            response['title_list'].append(article.title)

        response['count'] = info.aggregate(Count('id')).get('id__count')
        
        return JsonResponse(response,json_dumps_params={'ensure_ascii': False})
    
    ###添加数据
    def post(self, request):
        data = json.loads(request.body)
        print(data)

        au = models.Author.objects.create(
            name=data.get('name'),
            sex=data.get('sex'),
            age=data.get('age')
        )
        
        articles = [
            models.Article(
                title=article.get('title'),
                content=article.get('content'),
                published_time=article.get('published_time'),
                author=au
            )
            for article in data.get('article_list')
        ]
        
        models.Article.objects.bulk_create(articles)
        
        added_articles_count = models.Article.objects.filter(author=au).count()
        
        response = {
            "author_name": data.get('name'),
            "add_articles_count": added_articles_count
        }

        return JsonResponse(response, json_dumps_params={'ensure_ascii': False})
    
    ###修改数据
    def put(self, request):
        #修改作者某一篇文章的内容
        data = json.loads(request.body)
        print(data)

        article = models.Article.objects.filter(author__name=data.get('name')).first()
        article.content = data.get('content')
        article.save()

        response =  {
            "title": article.title,
            "content":article.content
        }

        return JsonResponse(response, json_dumps_params={'ensure_ascii': False})
    
    ###删除数据
    def delete(self, request):
        #根据文章标题删除作者的文章
        data = json.loads(request.body)
        print(data)
        del_article_id_list = []
        for title in data.get('del_title_list'):
            del_article = models.Article.objects.get(title=title, author__name=data.get('name'))
            del_article_id_list.append(del_article.id)
            del_article.delete()
        return JsonResponse({"del_article_id_list":del_article_id_list}, json_dumps_params={'ensure_ascii': False})